# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(tidyverse)
library(magrittr)
library(plotrix)
library(tools)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--config", default = "config.csv", type = "character", help = "config file"),
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file")
)
opt <- parse_args(OptionParser(option_list = option_list))
source(opt$base)

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

isCorExec <- configData["cor.isCorExec", "value"] == "T"

getClassCols <- function(n) {
  inCols <- c("#00FFFF", "#0099FF", "#8A4198", "#FF6F00", "#CC9999", "#FFFF00", "#00FF7F", "#999999", "#CCFFCC", "#336666",
              "#FF6666", "#FFCC33", "#CC3399")
  extraColors <- c("#CD0000", "#3A89CC", "#769C30", "#D99536", "#7B0078", "#BFBC3B", "#6E8B3D", "#00688B", "#C10077", "#CAAA76",
                   "#EEEE00", "#458B00", "#8B4513", "#008B8B", "#6E8B3D", "#8B7D6B", "#7FFF00", "#CDBA96", "#ADFF2F")
  orignalCols <- c(inCols, extraColors)
  on <- length(orignalCols)
  if (n <= on) {
    orignalCols[1:n]
  }else {
    ggCols <- gg_color_hue(n - on)
    c(orignalCols, ggCols)
  }
}

flower_plot <- function(sample, otu_num, core_otu, start, a, b, r, ellipse_col, circle_col) {
  par(bty = 'n', ann = F, xaxt = 'n', yaxt = 'n', mar = c(1, 1, 1, 1))
  plot(c(0, 10), c(0, 10), type = 'n')
  n <- length(sample)
  deg <- 360 / n
  res <- lapply(1:n, function(t) {
    draw.ellipse(x = 5 + cos((start + deg * (t - 1)) * pi / 180),
                 y = 5 + sin((start + deg * (t - 1)) * pi / 180),
                 col = ellipse_col[t],
                 border = ellipse_col[t],
                 a = a, b = b, angle = deg * (t - 1))
    text(x = 5 + 2.5 * cos((start + deg * (t - 1)) * pi / 180),
         y = 5 + 2.5 * sin((start + deg * (t - 1)) * pi / 180),
         otu_num[t])

    if (deg * (t - 1) < 180 && deg * (t - 1) > 0) {
      text(x = 5 + 3.3 * cos((start + deg * (t - 1)) * pi / 180),
           y = 5 + 3.3 * sin((start + deg * (t - 1)) * pi / 180),
           sample[t],
           srt = deg * (t - 1) - start,
           adj = 1,
           cex = 1
      )
    } else {
      text(x = 5 + 3.3 * cos((start + deg * (t - 1)) * pi / 180),
           y = 5 + 3.3 * sin((start + deg * (t - 1)) * pi / 180),
           sample[t],
           srt = deg * (t - 1) + start,
           adj = 0,
           cex = 1
      )
    }
  })
  draw.circle(x = 5, y = 5, r = r, col = circle_col, border = NA)
  text(x = 5, y = 5, paste('Core:', core_otu))
}

plotEmptyPage <- function(pdfFileName) {
  p <- ggplot() + theme_void()
  ggsave(limitsize = FALSE, pdfFileName, p, width = 8, height = 8)
}

plotEmptyPageAndExit <- function(pdfFileName) {
  plotEmptyPage(pdfFileName)
  quit(status = 0)
}

closeAndPlotEmptyPageAndExit <- function(pdfFileName) {
  dev.off()
  plotEmptyPageAndExit(pdfFileName)
}

deleteAndExit <- function(pdfFileName) {
  dev.off()
  file.remove(pdfFileName)
  quit(status = 0)
}

workspacePath <- "../../"

dir <- str_c(workspacePath)

dirs <- list.dirs(dir, recursive = F) %>%
  keep(~str_detect(.x, "_vs_")) %>%
  keep(function(dirName) {
    length <- basename(dirName) %>%
      str_split("_vs_") %>%
      unlist() %>%
      length()
    length == 2
  })
tmpTreats <- basename(dirs)

if (length(tmpTreats) == 0) {
  quit(status = 0)
}

uploadDirs <- str_c(workspacePath, "/cor_extra_data") %>%
  list.files(full.names = T) %>%
  basename() %>%
  file_path_sans_ext()
uploadDirs

if (!isCorExec) {
  quit(status = 0)
}

for (uploadDir in uploadDirs) {
  createWhenNoExist(uploadDir)
  dataList <- tmpTreats %>%
    map(function(treat) {
      subDir <- str_c(workspacePath, treat, "/cor/01")
      fileParent <- list.dirs(subDir, recursive = F) %>%
        keep(~str_detect(.x, "_and_")) %>%
        head(1)
      filePath <- str_c(fileParent, "/", uploadDir, "/Network_Nodes_for_Cytoscape.csv")
      nodes <- if (!file.exists(filePath)) {
        c()
      }else {
        read_csv(filePath) %>%
          .$Node
      }
      list(treat = treat, nodes = nodes)
    }) %>%
    discard(function(x) {
      is.null(x$nodes)
    })
  treats <- dataList %>%
    map_chr(~.x$treat)
  datas <- dataList %>%
    map(~.x$nodes) %>%
    purrr::set_names(treats)
  size <- length(treats)
  treatsStr <- treats %>%
    map_chr(~str_c(.x, "\n"))
  pdfFileName <- str_c(uploadDir, "/Inter_Correlation_Venn_Plot_By_TwoGroup_Compares.pdf")
  inDataFileName <- str_c(uploadDir, "/Inter_Correlation_Venn_Data_By_TwoGroup_Compares.csv")
  maxCharNum <- treatsStr %>%
    map_dbl(~str_length(.x)) %>%
    max()
  width <- 8 + maxCharNum * 1
  height <- width
  print(height)
  pdf(pdfFileName, width = width, height = height)
  par(mar = c(2, 0, 2, 6) + 0.1, family = "Times")
  plotData <- read_csv(inDataFileName)
  vennPlot(datas)
  dev.off()
}











